package com.woniu.atms.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张杰
 */
@Slf4j
//@Component
//@WebFilter(urlPatterns = "/*")
//@Order(1)
public class CorssFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //输出日志
        log.debug("访问WnCorsFilter");
        //配置全局跨域
        HttpServletRequest re = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //允许的域
        res.setHeader("Access-Control-Allow-Origin", "*");
        //允许浏览器携带cookie
        res.setHeader("Access-Control-Allow-Credentials", "true");
        //response.setHeader("Access-Control-Allow-Headers", "token");
        res.setHeader("Access-Control-Allow-Methods", "*");
        res.setHeader("Access-Control-Allow-Headers", "*");
        res.setHeader("Access-Control-Expose-Headers", "*");
        String method = re.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return;
        } else {
            filterChain.doFilter(re, res);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
